package com.tledu.dangjian.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tledu.dangjian.core.AjaxResult;
import com.tledu.dangjian.core.annotion.Auth;
import com.tledu.dangjian.core.constants.ErrorCodeConstants;
import com.tledu.dangjian.core.exception.UsernameRepeatException;
import com.tledu.dangjian.dao.IResourcesDao;
import com.tledu.dangjian.model.Resource;
import com.tledu.dangjian.model.Role;
import com.tledu.dangjian.service.IResourcesService;
import com.tledu.dangjian.service.IRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/resource")
@AllArgsConstructor
public class ResoucesCotroller {
    private IResourcesService resourcesService;

    @RequestMapping("/list")
    @Auth(auth = "resource")
    public String userList(Resource resources, @RequestParam(required = true) Integer pageNum, @RequestParam(required = true) Integer pageSize, Model model) {
        PageHelper.startPage(pageNum, pageSize);
        model.addAttribute("pageInfo", PageInfo.of(resourcesService.list(resources)));

        return "resources/list";
    }

//    @RequestMapping("/list")
//    public String userList(User user, Model model) {
//        //PageHelper.startPage(pageNum, pageSize);
//        model.addAttribute("list", userService.list(user));
//        return "user/list";
//    }

    @GetMapping("/add")
    public String add() {

        return "resources/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addActions(@RequestBody Resource resources) {
        resourcesService.insert(resources);
        return new AjaxResult("保存成功", null);
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable Integer id) {
        resourcesService.delete(id);
        return new AjaxResult("删除成功", null);
    }

    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        Resource resources = resourcesService.selectById(id);
        model.addAttribute("entity", resources);
        return "resources/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(Resource resources) {
        resourcesService.update(resources);
        return new AjaxResult("修改成功", null);
    }

    @ExceptionHandler(value = UsernameRepeatException.class)
    @ResponseBody

    public AjaxResult handleException(UsernameRepeatException e) {
        return new AjaxResult(e.getMessage(), ErrorCodeConstants.USERNAME_REPEAT, null);
    }
}